package com.atguigu.controller.front;

import com.atguigu.client.OrderClient;
import com.atguigu.domain.EduCourse;
import com.atguigu.domain.chapter.ChapterVo;
import com.atguigu.domain.frontvo.CourseFrontVo;
import com.atguigu.domain.frontvo.CourseWebVo;
import com.atguigu.service.EduChapterService;
import com.atguigu.service.EduCourseService;
import com.atguigu.utils.JwtUtils;
import com.atguigu.utils.R;
import com.atguigu.utils.ordervo.CourseWebVoOrder;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/eduservice/coursefront")
@CrossOrigin
public class CourseFrontController {
    @Autowired
    private EduCourseService eduCourseService;

    @Autowired
    private EduChapterService eduChapterService;

    @Autowired
    private OrderClient orderClient;

    @PostMapping("getFrontCourseList/{page}/{limit}")
    public R getFrontCourseList(@PathVariable long page,
                                @PathVariable long limit,
                                @RequestBody(required = false)CourseFrontVo courseFrontVo){
        Page<EduCourse> coursePage = new Page<>(page,limit);
        Map<String,Object> map = eduCourseService.getCourseFrontList(coursePage,courseFrontVo);
        return R.ok().data(map);
    }

    @GetMapping("getFrontCourseInfo/{courseId}")
    public R getFrontCourseInfo(@PathVariable String courseId, HttpServletRequest request){

        CourseWebVo courseWebVo = eduCourseService.getBaseCourseInfo(courseId);

        List<ChapterVo> chapterVideoList = eduChapterService.getChapterVideoByCourseId(courseId);

        String memberId = JwtUtils.getMemberIdByJwtToken(request);
        if(!memberId.isEmpty()){
            Boolean isBuy = orderClient.isBuyCourse(courseId, JwtUtils.getMemberIdByJwtToken(request));
            return R.ok().data("courseWebVo",courseWebVo).data("chapterVideoList",chapterVideoList)
                    .data("isBuy",isBuy);
        }
        return R.ok().data("courseWebVo",courseWebVo).data("chapterVideoList",chapterVideoList);



    }

    @PostMapping("getCourseInfoOrder/{id}")
    public CourseWebVoOrder getCourseInfoOrder(@PathVariable String id){
        CourseWebVo baseCourseInfo = eduCourseService.getBaseCourseInfo(id);
        CourseWebVoOrder courseWebVoOrder = new CourseWebVoOrder();
        BeanUtils.copyProperties(baseCourseInfo,courseWebVoOrder);
        return courseWebVoOrder;
    }


}
